<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Refund;
use app\common\model\Ann;
use app\common\model\Banner;
use app\common\model\campsite\Campsite as CampsiteCampsite;
use app\common\model\campsite\Order;
use think\Db;
use think\Validate;

/**
 * 营地接口
 */
class Campsite extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @ApiTitle (营地列表)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function lists()
    {
        $param = request()->param();
        extract($param);
        $model = new CampsiteCampsite();
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', '%' . $keywords . '%');
        }
        $lists = $model->where('status', 'normal')->order('id desc')->paginate();
        $this->success('请求成功', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (营地详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function info()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $data = CampsiteCampsite::get($id);
        $this->success('请求成功', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (立即预定)
     * @ApiMethod (POST)
     * @ApiParams (name="c_id", type="integer", required=true, sample="", description="营地ID")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量")
     * @ApiParams (name="reservetime", type="string", required=true, sample="", description="预定时间")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_reserve()
    {
        $param = request()->param();
        extract($param);
        $validate = new Validate([
            'c_id'   => 'require|gt:0',
            'num'  => 'require|gt:0',
            'reservetime'  => 'require',
        ], [
            'c_id.require'  => '参数错误',
            'reservetime.require' => '预定时间不能为空',
            'num.require' => '数量不能为空',
        ]);
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $info = CampsiteCampsite::get($c_id);

        if (!$info) {
            $this->error('信息为空');
        }
        if ($info->cart_space < $num) {
            $this->error('车位不足');
        }
        Db::startTrans();
        try {
            $time = time();
            $data = [
                'sn' => sn('campsite_order', 'sn', 'CP'),
                'title' => $info->title,
                'image' => $info->image,
                'user_id' => $this->auth->id,
                'c_id' => $c_id,
                'pay_price' => bcmul($info->price, $num, 2),
                'paytime' => $time,
                'num' => $num,
                'price' => $info->price,
                'reservetime' => $reservetime,
            ];
            $order = new Order($data);
            $order->allowField(true)->save();
            $info->cart_space = bcsub($info->cart_space, $num, 0);
            $info->save();
            queue('app\common\job\CampsiteOrder', $order->id, 300, '1255CampsiteOrder');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功', $order->id);
    }
    /**
     * @Author LK
     * @ApiTitle (预定列表)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function reserve_list()
    {
        $list = Order::with('campsite')->where('user_id', $this->auth->id)->where('order.status', '1')->order('order.id desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (预定详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function reserve_info()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $data = Order::get($id, ['campsite']);
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (取消预定)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="reason", type="integer", required=true, sample="", description="取消原因")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_reserver()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = Order::get($id);
        $day = config('site.cancel_day');
        Db::startTrans();
        try {
            $order = Order::get($id);
            $reservetime = strtotime($order->reservetime);
            if ($order->status == 0) {
                Order::where('id', $order['id'])->where('status', '0')->update(['status' => '-1', 'reason' => $reason]);
            } else {
                if (time() > bcsub($reservetime, $day, 0)) {
                    exception(__('预定时间前%d天不能取消', [$day]));
                }
                $res = Refund::refund($order->sn, $order->pay_price);
                if ($res == true) {
                    $order->status = '-1';
                    $order->canceltime = time();
                    $order->save();
                } else {
                    exception('退款失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }
    /**
     * @Author LK
     * @ApiTitle (删除订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
}
